from flask import Flask, render_template
import threading
import json
from miner import Miner, start_miner, miner_info
from p2p_server import start_p2p, broadcast_info, is_async_block_chain
from block_chain import get_host_ip

app = Flask(__name__)


# 矿工对象
miner = Miner()

# 开启广播监听线程
p2p_tread = threading.Thread(target=start_p2p)
p2p_tread.start()


@app.route('/')
def index_page():
    return render_template('index.html')


@app.route('/blocks')
def query_all_block():
    # 打开读取blocks.json
    file = open('static/blocks.json', 'r', encoding='utf-8')
    return file.read(), 200, {"Content-Type": "application/json;charset:utf-8;"}


@app.route('/miner/start')
def start_to_miner():
    if Miner.thread_flag:
        return "挖矿已开始，请勿重复操作"
    else:
        Miner.thread_flag = True
        Miner.miner_thread = threading.Thread(target=start_miner)
        Miner.miner_thread.start()
        print("开始挖矿")
        return "开始挖矿"


@app.route('/miner/stop')
def stop_miner():
    Miner.thread_flag = False
    print("停止挖矿")
    return "停止挖矿"


@app.route('/miner/info')
def get_miner_info():
    return json.dumps(miner_info), 200, {"Content-Type": "application/json;charset:utf-8;"}


@app.route('/broadcast/info')
def get_broadcast_info():
    return json.dumps(broadcast_info), 200, {"Content-Type": "application/json;charset:utf-8;"}


if __name__ == '__main__':
    # 开启flask服务器
    app.run(host=get_host_ip(), port=5000)
